package com.atguigu.gmall.scheduled.handler;

import com.atguigu.gmall.scheduled.entity.CartItem;
import com.atguigu.gmall.scheduled.mapper.CartItemMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class CartExceptionJobHandler {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CartItemMapper cartItemMapper;
    String cartException = "cart:exception:userIds";
    String cartPrefix = "cart:items:";
    Gson gson  = new Gson();
    @XxlJob("cartExceptionJobHandler")
    public ReturnT<String> exceptionHandle(){
        //处理异步任务失败的 购物项操作
        /*
        1、需要从redis中获取  userId集合
                整合redis
        2、需要操作cart数据库表
                整合mysql
         */
        /*
            获取redis中cart:exception:userIds  key的List值集合
            从右开始获取userId，如果有，遍历userId，每一个userId，先删除数据库userId的购物项数据
            然后使用userId查询redis中该用户的购物车数据  存入数据库中
         */
        BoundListOperations<String, String> listOps = redisTemplate.boundListOps(cartException);
        if(listOps.size()==0){//没有异常的userId
            return ReturnT.SUCCESS;
        }
        String userId = listOps.rightPop();//从右消费一个元素
        while(!StringUtils.isEmpty(userId)){
            //删除数据库userId的数据
            cartItemMapper.delete(new LambdaQueryWrapper<CartItem>().eq(CartItem::getUserId , userId));
            //获取该用户在redis中的购物车遍历将购物项存入到数据库中
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartPrefix + userId);
            if(hashOps.size()>0){
                List<Object> cartItemJsons = hashOps.values();
                cartItemJsons.forEach(cartItemJson->{
                    CartItem cartItem = gson.fromJson(cartItemJson.toString(), CartItem.class);
                    cartItemMapper.insert(cartItem);
                });
            }
            userId = listOps.rightPop();
        }
        return ReturnT.SUCCESS;
    }
}
